package com.leetcodehot.problems;

public class problems445 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseListNode(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1.val == 0 || l2.val == 0) {
            return l1.val == 0 ? l2 : l1;
        }
        l1 = reverseListNode(l1);
        l2 = reverseListNode(l2);
        int carry = 0;
        ListNode res = new ListNode(0);
        ListNode cur = res;
        while (l1 != null && l2 != null) {
            int x = (l1.val + l2.val + carry) % 10;
            carry = (l1.val + l2.val + carry) / 10;
            ListNode listNode = new ListNode(x);
            cur.next = listNode;
            cur = listNode;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            int x = (l1.val + carry) % 10;
            carry = (l1.val + carry) / 10;
            ListNode listNode = new ListNode(x);
            cur.next = listNode;
            cur = listNode;
            l1 = l1.next;
        }
        while (l2 != null) {
            int x = (l2.val + carry) % 10;
            carry = (l2.val + carry) / 10;
            ListNode listNode = new ListNode(x);
            cur.next = listNode;
            cur = listNode;
            l2 = l2.next;
        }
        if (carry > 0) {
            ListNode listNode = new ListNode(carry);
            cur.next = listNode;
            cur = listNode;
        }
        res = reverseListNode(res.next);
        return res;
    }
}
